//
//  BandConfigManager.swift
//  DaRings
//
//  Created by 尹琼 on 2023/2/27.
//

import UIKit
import HandyJSON
import Moya
import SDWebImage

open class BandConfigManager: NSObject {
    
    
    fileprivate let tripleDESDecryptor = TripleDESDecryptor()
    
   
    public static let shared = BandConfigManager()
    
    
    override init() {
        super.init()
        
     
        // 数据库是空的
        guard let model = BandConfigListModel.current(), let _ = model.v else {
            
            // 加载本地
            let model = self.defaultBandConfigListModel()
            model?.saveAll()
            
            return
        }
        
        
    }
    
        
    public func updateConfig() {
        
        
        guard let model = BandConfigListModel.current(), let v = model.v else {
            Swift.fatalError("本地配置文件不存在，请配置")
//            return
        }
        
        request(version: v, sucess: nil, error: nil)

        
    }
    
    
    /// 请求配置文件
    /// - Parameter version: 接口版本
    func request(version: Int, sucess: ((_ model: BandConfigListModel) ->Void)?, error: (() ->Void)?) {
        
        // 请求最新的
        API.bandConfig(target: .config(version: version)).response { response in
            
            if response.statusCode != 200 {
                error?()
                return
            }
            
            guard let text = String(data: response.data, encoding: .utf8),
                  let json = self.tripleDESDecryptor.encrypt(text: text),
                  let model = BandConfigListModel.deserialize(from: json) else {
                error?() // 接口错误
                return
            }
            
            // code = -3 代表当前你本地的版本是最新的，不需要去解析
            if model.code != 0 {
                return
            }
            
            self.clearnImageCache()
            model.saveAll()
            model.deletedAll()
            
            sucess?(model)
            
            
        } failure: { _ in
            
            error?()
            
        }
        
    }
    
    
    
    /// 本地默认配置
    /// - Returns: model
    func defaultBandConfigListModel() ->BandConfigListModel? {
        
        guard
            let filePath = self.filePath("BandingConfig", ofType: "json"),
            let jsonStr = decrptLocalFile(with: filePath) else {
            
            Swift.fatalError("本地未有配置文件/解析出错")
        }
        
        let model = BandConfigListModel.deserialize(from: jsonStr)
        return model
        
    }
    
    
    func clearnImageCache() {
        
        DispatchQueue.main.async {
            SDImageCache.shared.clearMemory()
        }

    }
    
    
    
    /// 路径
    /// - Parameters:
    ///   - name: 文件名
    ///   - ofType: 文件类型
    /// - Returns: 路径
    func filePath(_ name: String, ofType: String) -> String? {
        
        guard let jsonPath = Bundle.main.path(forResource: name, ofType: ofType) else {
            return Bundle(for: Self.self).path(forResource: name, ofType: ofType)
        }
        
        return jsonPath
    }
    
    /// 解密本地配置文件
    /// - Parameter path: 文件路径
    /// - Returns: 解密的文
    func decrptLocalFile(with path: String) ->String? {
        
        guard let dataString = try? String(contentsOfFile: path, encoding: .utf8),
              let jsonStr = self.tripleDESDecryptor.decrpt(text: dataString) else {
            return nil
        }
        
        return jsonStr
    }
}



